import { generateRandomId } from '@/lib/utils';
import { OperationMessage, useMessageStore } from '@/store/message';
let gigaOperationMessages: OperationMessage[] = [];

export function useMessage() {
  const dispatch = useMessageStore((state) => state.dispatch);

  function resetMessage() {
    // gigaOperationMessages = [];
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.gigaOperationMessages = [];
      },
    });
  }

  function addMessage(message: Omit<OperationMessage, 'id'>) {
    // console.log(message.type, message.message);
    // gigaOperationMessages.push({
    //   ...message,
    //   id: generateRandomId(),
    // });
    dispatch({
      type: 'update',
      update(draftState) {
        draftState.gigaOperationMessages.push({
          ...message,
          id: generateRandomId(),
        });
      },
    });
  }

  function resetAndAddMessage(message: Omit<OperationMessage, 'id'>) {
    // 移除所有相关类型的信息
    // const catetory = message.category;
    // const firstMessageIndex = gigaOperationMessages.findIndex((item) => item.category === catetory);
    // if (firstMessageIndex > -1) {
    //   // 执行替换操作
    //   gigaOperationMessages = gigaOperationMessages.filter((item) => item.category !== catetory);
    //   gigaOperationMessages.splice(firstMessageIndex, 0, {
    //     ...message,
    //     id: generateRandomId(),
    //   });
    // } else {
    //   gigaOperationMessages.push({
    //     ...message,
    //     id: generateRandomId(),
    //   });
    // }
    dispatch({
      type: 'update',
      update(draftState) {
        // 移除所有相关类型的信息
        const catetory = message.category;
        const firstMessageIndex = draftState.gigaOperationMessages.findIndex(
          (item) => item.category === catetory,
        );
        if (firstMessageIndex > -1) {
          // 执行替换操作
          draftState.gigaOperationMessages = draftState.gigaOperationMessages.filter(
            (item) => item.category !== catetory,
          );
          draftState.gigaOperationMessages.splice(firstMessageIndex, 0, {
            ...message,
            id: generateRandomId(),
          });
        } else {
          draftState.gigaOperationMessages.push({
            ...message,
            id: generateRandomId(),
          });
        }
      },
    });
  }

  return {
    resetMessage: useCallback(resetMessage, []),
    addMessage: useCallback(addMessage, []),
    resetAndAddMessage: useCallback(resetAndAddMessage, []),
  };
}
